<script setup>
import { getGoodFilterService } from '@/apis/category'
import { onMounted, ref, watch } from 'vue';
import { useRoute } from 'vue-router';
import GoodsItem from '../Home/components/GoodsItem.vue';

const route = useRoute()
// 获取基础列表数据渲染
const goodList = ref([])
const name = ref(route.params.name); // 获取传递过来的搜索关键词

const fetchGoodsList = async () => {
    // 调用API获取商品列表
    const res = await getGoodFilterService({
        name: name.value
    })
    // 将获取到的数据赋值给data
    goodList.value = res.data.items;

}

onMounted(() => {
    // 在组件挂载后获取商品列表数据
    fetchGoodsList();
});

watch(
    () => route.params.name,
    (newValue, oldValue) => {
        if(newValue !== oldValue){
            name.value = newValue
            fetchGoodsList()
            reqData.value.name = newValue
            reqData.value.page = 1
            load()
        }
})

const reqData = ref({
    name: name.value,
    page: 1,
    pageSize: 5
})
// 无限滚动加载
const disabled = ref(false)
const load = async () => {
    // 获取下一页数据
    reqData.value.page++
    const res = await getGoodFilterService(reqData.value)
    // 展开运算符拼接新老数据
    goodList.value = [...goodList.value, ...res.data.items]
    // 加载完毕 停止监听
    if (res.data.items.length === 0) {
        disabled.value = true
    }
}

</script>

<template>
    <div class="container ">
        <div class="sub-container">
            <div class="body" v-infinite-scroll="load" :infinite-scroll-disabled="disabled">
                <!-- 商品列表-->
                <GoodsItem v-for="goods in goodList" :goods="goods" :key="goods.id" />
            </div>
        </div>
    </div>

</template>



<style lang="scss" scoped>
.bread-container {
    padding: 25px 0;
    color: #666;
}

.sub-container {
    padding: 20px 10px;
    background-color: #fff;

    .body {
        display: flex;
        flex-wrap: wrap;
        padding: 0 10px;
    }

    .goods-item {
        display: block;
        width: 220px;
        margin-right: 20px;
        padding: 20px 30px;
        text-align: center;

        img {
            width: 160px;
            height: 160px;
        }

        p {
            padding-top: 10px;
        }

        .name {
            font-size: 16px;
        }

        .desc {
            color: #999;
            height: 29px;
        }

        .price {
            color: $priceColor;
            font-size: 20px;
        }
    }

    .pagination-container {
        margin-top: 20px;
        display: flex;
        justify-content: center;
    }


}
</style>